import time

from django.conf import settings
from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from datetime import date
# Create your views here.
from django.template import loader, RequestContext
from django.urls import reverse
from django.core.paginator import Paginator
from booktest.models import BookInfo, PicTest, AreaInfo, GoodsInfo


def temp_filter(request):
	context = {'list': BookInfo.objects.all()}
	return render(request, 'booktest/temp_filter.html', context)


def temp_inherit(request):
	return render(request, 'booktest/temp_inherit.html',
	              {'title': '末班继承', 'list': BookInfo.objects.all(), 'content': '<h1>张涵弈</h1>'})


def index(request):
	# # return HttpResponse('老铁没毛病')
	# # 加载模板文件
	# temp = loader.get_template('booktest/index.html')
	# # 定义模板上下文
	# context = RequestContext(request, {})
	# # 产生标准的html
	# res_html = temp.render(context)
	# return HttpResponse(res_html)
	return render(request, 'booktest/index.html', {'context': '不错啊不错啊', 'list': list(range(0, 10))})


def show_books(request):
	"""显示图书的信息"""
	remote_ip = request.META['REMOTE_ADDR']
	print(str(remote_ip))
	if "username" in request.session:  # 推荐用这个
		print('有这个session key')
	if request.session.has_key('username') and request.session.get('username') == 'zhy':
		books = BookInfo.objects.exclude(isDelete=1)
		# return render(request, 'booktest/show_books.html', {'books': books, 'ALI_MEDIA_URL': settings.ALI_MEDIA_URL})
		return render(request, 'booktest/show_books.html', {'books': books})
	else:
		# return render(request, 'booktest/login.html', {"username": request.COOKIES.get('username', '')})
		return redirect('/login', username=request.COOKIES.get('username', ''))


def detail(request, bid):
	"""查询图书关联信息"""
	book = BookInfo.objects.get(id=bid)
	heroes = book.heroinfo_set.all()
	return render(request, 'booktest/detail.html', {'book': book, 'heroes': heroes})


def create(request):
	"""新增一本图书"""
	book = BookInfo()
	book.btitle = '流星蝴蝶剑'
	book.bpub_date = date(1995, 12, 30)
	book.save()
	# 转向首页
	return redirect('/books')


def delete(request, bid):
	"""删除一本图书"""
	book = BookInfo.objects.get(id=int(bid))
	book.isDelete = 1
	book.save()
	return redirect(reverse('booktest:books'))  # 反向解析也可以应用在视图的重定向中


def login(request):
	"""显示登录页面"""
	# return HttpResponse('没有问题的')
	return render(request, 'booktest/login.html', {"username": request.COOKIES.get('username', '')})


def login_check(request):
	"""登录校验"""
	username = request.POST.get('username')
	password = request.POST.get('password')
	remember = request.POST.get('remember')
	if username == 'zhy' and password == '123':
		response = JsonResponse({"status": 'ok', "code": 200})
		request.session['username'] = username
		request.session.set_expiry(3600)
		if remember == 'true':
			response.set_cookie('username', username, max_age=3600)
		else:
			response.delete_cookie('username')
		return response
	else:
		return JsonResponse({"status": 'error'})


def show_upload(request):
	"""上传图片界面"""
	return render(request, 'booktest/upload_pic.html')


def area(request):
	areas = AreaInfo.objects.get(pk=440100)
	return render(request, 'booktest/area.html', {'area': areas})


# def verify_code(request):
# 	# 引入随机函数模块
# 	import random
# 	# 定义变量，用于画面的背景色、宽、高
# 	bgcolor = (random.randrange(20, 100), random.randrange(
# 		20, 100), 255)
# 	width = 100
# 	height = 25
# 	# 创建画面对象
# 	im = Image.new('RGB', (width, height), bgcolor)
# 	# 创建画笔对象
# 	draw = ImageDraw.Draw(im)
# 	# 调用画笔的point()函数绘制噪点
# 	for i in range(0, 100):
# 		xy = (random.randrange(0, width), random.randrange(0, height))
# 		fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
# 		draw.point(xy, fill=fill)
# 	# 定义验证码的备选值
# 	str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
# 	# 随机选取4个值作为验证码
# 	rand_str = ''
# 	for i in range(0, 4):
# 		rand_str += str1[random.randrange(0, len(str1))]
# 	# 构造字体对象，ubuntu的字体路径为“/usr/share/fonts/truetype/freefont”
# 	font = ImageFont.truetype('FreeMono.ttf', 23)
# 	# 构造字体颜色
# 	fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
# 	# 绘制4个字
# 	draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
# 	draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
# 	draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
# 	draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
# 	# 释放画笔
# 	del draw
# 	# 存入session，用于做进一步验证
# 	request.session['verifycode'] = rand_str
# 	# 内存文件操作
# 	buf = BytesIO()
# 	# 将图片保存在内存中，文件类型为png
# 	im.save(buf, 'png')
# 	# 将内存中的图片数据返回给客户端，MIME类型为图片png
# 	return HttpResponse(buf.getvalue(), 'image/png')


def upload_handle(request):
	"""上传图片处理"""
	# 获取上传图片的处理对象
	pic = request.FILES['pic']

	# 创建一个文件
	save_path = "%s/booktest/%s" % (settings.MEDIA_ROOT, pic.name)
	# 获取上传文件的内容并写入船舰的文件中
	with open(save_path, 'wb') as f:
		for content in pic.chunks():
			f.write(content)
		# 在数据库中保存上传的记录
		PicTest.objects.create(goods_pic='booktest/%s' % pic.name)
	# 返回
	return HttpResponse('ok')


def area_pagination(request, p_index):
	temp_list = AreaInfo.objects.filter(p__isnull=True)
	pp = Paginator(temp_list, 10)
	print(p_index)
	if p_index == '' or p_index is None:
		p_index = 1
	p_index = int(p_index)
	listt = pp.page(p_index)
	plist = pp.page_range
	return render(request, 'booktest/page_area.html', {'page': listt, 'plist': plist})


def editor(request):
	return render(request, 'booktest/editor.html')


def show(request):
	goods = GoodsInfo.objects.get(id=1)
	context = {'g': goods.getcontent}
	return render(request, 'booktest/show.html', context)


def sayhello(request):
	print('Hello ...')
	time.sleep(2)
	print('sleep ...')
	return HttpResponse('hello world')

